﻿//公共函数
//获取对象属性数量
var async = require('async');
var https = require('https');
var fs = require('fs');
var file = "config.json";
var result = JSON.parse(fs.readFileSync(file));
var conn;
var pool;

var APP_ID = result.APP_ID;//小程序appid  
var APP_SECRET = result.APP_SECRET;//小程序app_secret
var db_host = result.db_host;
var db_user = result.db_user;
var db_pwd = result.db_pwd;//yhx**0532%&* 123
var database = result.database;
var db_port = result.db_port;

//console.log("APP_SECRET:"+APP_SECRET);
module.exports.arraySize = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};
//测试方法
module.exports.test = function(obj) {
    return "Hello "+obj;
};
//测试方法:如何调用公共函数
module.exports.test2 = function(obj) {
    return module.exports.test(obj);
};
//对象转Json
module.exports.objectToJson = function(obj) {
	return JSON.stringify(obj);
};
//获取在线用户人数
module.exports.getRoomCount = function(sockets) {
	var count = 0;
	for (var i in sockets.adapter.rooms) {
		count++;
	}
	var size = (count == 0?0:(count-module.exports.arraySize(sockets.adapter.sids)));
	return size;
}
//分配房间内的位子
module.exports.admeasureRoomIndex = function(rooms,connectionList,name) {
	var index = 0;
	var bo = true;
	while(bo) {
		for (var i in rooms) {
			var socketId = rooms[i];
			if(typeof(connectionList[socketId]) == "undefined") {
				  continue;
			}
			if(typeof(connectionList[socketId].name) == name) {
				  continue;
			}
			if(connectionList[socketId].roomIndex == index) {
				bo = false;
				index++;
				break;
			} 
		}
		if(bo) break;
		else   bo = true;
	}
	return index;
}
//获取指定用户是否在线
module.exports.isOnline = function(sockets,name) {
    var count = module.exports.arraySize(sockets.adapter.rooms[name]);
	return module.exports.objectToJson({isOnline:count > 0?true:false})
};
//获取指定用户打开窗口的数量
module.exports.getMemberCountByRoom = function(sockets,name) {
    return module.exports.arraySize(sockets.adapter.rooms[name]);
};
//redis消息订阅
module.exports.subscribeRedis = function(redisclient,c) {
    var c = c || 'chatchannel';
    redisclient.subscribe(c, function(e) {
     //   console.log('subscribe channel : ' + c);
    });
}
//发送http的POST请求
module.exports.sendLog = function (req, res,obj,callback) {
    //	data = JSON.stringify(data);  
		data = require('querystring').stringify(obj);  
        var postheaders = {
          "Content-Type": 'application/x-www-form-urlencoded',
		// "Content-Type": 'application/json',
		  "Content-Length": data.length
        };  
        var opt = {
            host : 'www.see.com',  
            port : '80',  
            path : "/index.php/Home/Index/write",
            method : 'POST',  
            headers : postheaders  
        };
		var http = require('http');
		var request = http.request(opt, function (serverFeedback) {
        if (serverFeedback.statusCode == 200) {  
            var body = "";  
            serverFeedback.on('data', function (data) { body += data; })  
                          .on('end', function () {
						  callback(body);
							//res.send(200, body); 
					//		console.log(body);
					//		return body;
			});  
        }  
        else {
            res.send(500, "error");  
        }  
    });
    request.write(data + "\n");  
    request.end();
}
//连接Redis
module.exports.getRedisClient = function() {
	var redis = require('redis');
	var redisclient = redis.createClient(6379,'120.27.54.128');
	redisclient.auth("ysd123", function() {
		//console.log("redis通过认证");
	});
	return redisclient;
}

//操作mysql
module.exports.insertOrUpdate = function () {
	//插入数据库
	 var sys = require('sys');
	 var mysql = require('mysql');
	 var conn = mysql.createConnection({
		host: db_host,
		user: db_user,
		password: db_pwd,
		database:database,
		port: db_port
	 });
	 conn.connect();
	 var values = [response, '18'];
	 conn.query('INSERT INTO think_test SET name = ?, age = ?', values,
	 function(error, results) {
		if(error) {
		//	console.log("ClientReady Error: " + error.message);
			client.end();
			return;
		}
	//	console.log('Inserted: ' + results.affectedRows + ' row.');
	//	console.log('Id inserted: ' + results.insertId);
	 }
	);
	conn.end();
}
//操作mysql
module.exports.initPool = function () {
	var mysql = require('mysql');
	pool = mysql.createPool({
		host: db_host,
		user: db_user,
		password: db_pwd,
		database:database,
		port: db_port
	});
}
module.exports.initConn = function () {
	var util = require('util');
	 var mysql = require('mysql');
	 conn = mysql.createConnection({
		host: db_host,
		user: db_user,
		password: db_pwd,
		database:database,
		port: db_port
	 });
	 conn.connect();
	 conn.on('error', function(err) {
		console.log('db error:', err);
		if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
			module.exports.initConn();                         // lost due to either server restart, or a
		} else {                                      // connnection idle timeout (the wait_timeout
		  throw err;                                  // server variable configures this)
		}
	 });
	/*var Client = require('easymysql');
	mysql = Client.create({
	  'maxconnections' : 10
	});
	mysql.addserver({
	  'host' : '127.0.0.1',
	  'user' : 'root',
	  'password' : '123',
	  'database':'answer'
	});
	
	mysql.query('USE answer', function (error, res) {
		  console.log(res);
	});*/
	/*
	mysql.addserver({
	  'host' : '127.0.0.1',
	  'user' : 'read_user',
	  'password' : ''
	});*/
}
module.exports.getPool = function () {
	return pool;
}
module.exports.getConn = function () {
	return conn;
}
/*
module.exports.getConn = function () {
	 if(connInstance) return connInstance;
	 var util = require('util');
	 var mysql = require('mysql');
	 var conn = mysql.createConnection({
		host: '127.0.0.1',
		user: 'root',
		password: '123',
		database:'answer',
		port: 3306
	 });
	 conn.connect();
	 connInstance = conn;
	 return conn;
}*/
//从数组中随机获取数据
module.exports.getRandomArrayElements = function (arr, count) {
	var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
	while (i-- > min) {
		index = Math.floor((i + 1) * Math.random());
		temp = shuffled[index];
		shuffled[index] = shuffled[i];
		shuffled[i] = temp;
	}
	return shuffled.slice(min);
}

//为比赛者提供7个随机大类供选择
module.exports.getSevenClassifies = function (id) {
	pool.getConnection(function (err, conn) {
		if (err) {
			console.log("POOL ==> " + err);
			return;
		}
		if(global.battles[id]) global.battles[id].sevenClassifies = [];
		else return;
	//	conn = module.exports.getConn();
		var sql = 'SELECT * FROM `answer_classify` WHERE  `type`=?  AND `status`=? ORDER BY RAND() LIMIT ?';
		conn.query(sql, [1,1,5],function(error, classifies) {
				if(error) {
					return;
				}
				if(classifies.length > 0) {
					for (var j in classifies) {
						var classify = classifies[j];
						global.battles[id].sevenClassifies.push({id:classify['id'],name:classify['name'],type:classify['type']});
					}
				}
			}
		);
		sql = 'SELECT * FROM `answer_classify` WHERE  `type`=?  AND `status`=? ORDER BY RAND() LIMIT ?';
		conn.query(sql, [2,1,1],function(error, classifies) {
				if(error) {
					return;
				}
				if(classifies.length > 0) {
					for (var j in classifies) {
						var classify = classifies[j];
						global.battles[id].sevenClassifies.push({id:classify['id'],name:classify['name'],type:classify['type']});
					}
				}
			}
		);
		sql = 'SELECT * FROM `answer_classify` WHERE  `type`=?  AND `status`=? ORDER BY RAND() LIMIT ?';
		conn.query(sql, [3,1,1],function(error, classifies) {
				if(error) {
					return;
				}
				if(classifies.length > 0) {
					for (var j in classifies) {
						var classify = classifies[j];
						global.battles[id].sevenClassifies.push({id:classify['id'],name:classify['name'],type:classify['type']});
					}
				}
			}
		);
		conn.release();
	});
}
//为房间生成随机大类
module.exports.makeRandomClassifies = function (id) {//房间id
	pool.getConnection(function (err, conn) {
		if (err) {
			console.log("POOL ==> " + err);
			return;
		}
	//	conn = module.exports.getConn();
		var sql = 'SELECT * FROM `answer_classify` WHERE `status`=? ORDER BY RAND() LIMIT ?';
		conn.query(sql, [1,2],
			function(error, classifies) {
				if(error) {
			//		console.log("ClientReady Error: " + error.message);
				//	conn.end();
					return;
				}
				if(classifies.length > 0) {
					for (var j in classifies) {
						var classify = classifies[j];
			//			console.log("Random classify:"+classify['id']);
						module.exports.makeRandomQuestion(id,classify['id']);
					}
				}
			}
		);
		conn.release();
	});
}
//判断数组中是否包含指定元素
module.exports.contains = function (arr,data) {
	for(var i = 0;i < arr.length;i++) {
		if(arr[i] == data) {
			return true;
		}
	}	
	return false;
}
//为天梯房间生成题目
module.exports.fillQuestionForRoom = function (id) {//房间id
	if(!global.battles[id]) return;
	var battle = global.battles[id];
	if(battle.gameClassifies.length != 2) return;
		async.auto({
			getCount: function (callback) {
				var where = '';
				for(var row in battle.gameClassifies) {
					where = where +','+battle.gameClassifies[row];
				}
				where = where.substring(1);
				pool.getConnection(function (err, conn) {
					if (err) {
						console.log("POOL ==> " + err);
						return;
					}
					conn.query("SELECT classifyID,count(id) len FROM `view_question` WHERE `status`=? AND is_ladders=? AND classifyID IN ("+where+") GROUP BY classifyID", [1,1],function(error, views) {
						if(error) {
							return;
						}
						var counts = {};
						if(views.length > 0) {
							for (var i in views) {
								var view = views[i];
								counts[view['classifyID']] = view['len'];
							}
						}
						callback(null, counts);
					});
					conn.release();
				});
			},
			fillQuestion: ['getCount', function(callback,data) {
				var totals = data.getCount;
				pool.getConnection(function (err, conn) {
					if (err) {
						console.log("POOL ==> " + err);
						return;
					}
					for(var row in battle.gameClassifies) {
						var cid = battle.gameClassifies[row];
						var data = [];
						for(var uid in battle.players) {
							if(typeof(global.playerData[uid]) == "undefined") continue;
							if(typeof(global.playerData[uid][cid]) == "undefined") continue;
							var list = global.playerData[uid][cid];
							for(var i in list) {
								if(!module.exports.contains(data,list[i])) data.push(list[i]);
							}
						}
						var sql = '';
						var args = [1,1,cid,5];
						if(data.length == 0) {
							sql = 'SELECT * FROM `view_question` WHERE `status`=? AND is_ladders=? AND classifyID=? ORDER BY RAND() LIMIT ?';
					//		console.log(cid+':无历史答题记录,直接随机');
						} else {
							//判断题目总数 - 对战双方已答题总和 是否大于等于 5 (是否答穿题库)
							if(totals[cid] - data.length < 5) {
								sql = 'SELECT * FROM `view_question` WHERE `status`=? AND is_ladders=? AND classifyID=? ORDER BY RAND() LIMIT ?';
					//			console.log(cid+':题库已被答穿,直接随机');
							} else {
								var str = '';
								for(var i in data) {
									str = str +','+data[i]
								}
								str = str.substring(1);
								sql = 'SELECT * FROM `view_question` WHERE `status`=? AND is_ladders=? AND classifyID=? AND id NOT IN('+str+') ORDER BY RAND() LIMIT ?';
							//	console.log(cid+':去除已答题目:'+str);
							}
						}
						conn.query(sql, args,function(error, views) {
							if(error) {
								console.log("ClientReady Error: " + error.message);
							//	conn.end();
								return;
							}
							var qids = '';
							var pid = '';
							if(views.length > 0) {
								for (var i in views) {
									var view = views[i];
									qids +=view['id']+',';
									pid = view['classifyID']
								}
								if(qids.length > 0) qids = qids.substring(0,qids.length-1);
								module.exports.fillQuestion(id,qids);
								//console.log(pid+':最终随机ID:'+qids);
							}
						});
					}
					conn.release();
				});
				callback();
			}]
		}, function(err, results) {
		//	console.log('1.1: err: ', err); 
		//	console.log('1.1: results: ', results);
		});
	//	conn = module.exports.getConn();
	//	console.log("fillQuestion: " + id);
}
//为房间生成随机题目
module.exports.makeRandomQuestion = function (id,classifyID) { //房间id,类目ID
	pool.getConnection(function (err, conn) {
		if (err) {
			console.log("POOL ==> " + err);
			return;
		}
	//	conn = module.exports.getConn();
		var sql = 'SELECT * FROM `view_question` WHERE `status`=? AND is_ladders=? AND classifyID=? ORDER BY RAND() LIMIT ?';
		conn.query(sql, [1,1,classifyID,5],
			function(error, views) {
				if(error) {
			//		console.log("ClientReady Error: " + error.message);
				//	conn.end();
					return;
				}
				var qids = '';
				if(views.length > 0) {
					for (var i in views) {
						var view = views[i];
					//	console.log("Random Question:"+view['id']);
						qids +=view['id']+',';
					//	module.exports.addRandomQuestions(id,classify['id']);
					}
					if(qids.length > 0) qids = qids.substring(0,qids.length-1);
					module.exports.fillQuestion(id,qids);
				}
			}
		);
		conn.release();
	});
}
//为房间填充指定题目
module.exports.fillQuestion = function (id,qids) {//房间id,题目id数组
	pool.getConnection(function (err, conn) {
		if (err) {
			console.log("POOL ==> " + err);
			return;
		}
	//	conn = module.exports.getConn();
		conn.query('SELECT q.*,c.`name`,u.account FROM answer_question q LEFT JOIN answer_user u ON u.id=q.authorID LEFT JOIN answer_classify c ON c.id=q.classifyID WHERE q.id IN('+qids+')', [],
			function(error, questions) {
				if(error) {
			//		console.log("ClientReady Error: " + error.message);
				//	conn.end();
					return;
				}
				if(questions.length > 0) {
					var count = 0;
					for (var j in questions) {
						var question = questions[j];
					//	console.log("为题目"+question['id']+"加载选项");
						module.exports.addOptions(id,question,2);
						count++;
					}
			//		console.log("Room : " + id + " : Add " +count+" totals");
				}
			}
		);
		conn.release();
	});
}
//结算玩家分数
module.exports.balanceCups = function (battle) {
	var points = [];
	var names = [];
	for(var uid in battle.players) {
		var player = battle.players[uid];
	//	console.log("player:"+uid+", points:"+player.point+" , cups:"+player.cups);
		points.push({id:uid,point:player.point,cups:player.cups});
		names.push(player.name);
	}
	if(points.length != 2) {
	//	console.log('结算分数异常');
		return;
	}
	if(points[0].point != points[1].point) {
		//天梯匹配ELO算法计算公式
		var cha = 0;
		if (points[0].cups > points[1].cups) cha = points[0].cups - points[1].cups;
		else cha = points[1].cups - points[0].cups;
		cha = cha/400;
		var a = 1/(1+Math.pow(10,cha));
		var Ea = a.toFixed(2);
		var Eb = 1-Ea;
		var p1 = Math.round(32*(1-Ea));
		var p2 = Math.round(32*(1-Eb));
		var t = require('silly-datetime');
		var time = t.format(new Date(), 'HH:mm');
		if (points[0].point > points[1].point && points[0].cups >= points[1].cups) {
			battle.ELO = p2;
			battle.winner = points[0].id;
			module.exports.updatePoint(points[0].id,parseInt(points[0].cups) + p2);
			module.exports.updatePoint(points[1].id,points[1].cups - p2);
			module.exports.writeLog(names[0]+" 与 "+names[1]+" 对战结束 , "+names[0]+" 胜利");
			global.sockets.in('ladder').emit('comment', {content:names[0]+" 与 "+names[1]+" 对战结束 , "+names[0]+" 胜利",time:time});
			global.sockets.in('admin').emit('comment', {content:names[0]+" 与 "+names[1]+" 对战结束 , "+names[0]+" 胜利",time:time});
		} else if(points[0].point > points[1].point && points[0].cups < points[1].cups) {
			battle.ELO = p1;
			battle.winner = points[0].id;
			module.exports.updatePoint(points[0].id,parseInt(points[0].cups) + p1);
			module.exports.updatePoint(points[1].id,points[1].cups - p1);
			module.exports.writeLog(names[0]+" 与 "+names[1]+" 对战结束 , "+names[0]+" 胜利");
			global.sockets.in('ladder').emit('comment', {content:names[0]+" 与 "+names[1]+" 对战结束 , "+names[0]+" 胜利",time:time});
			global.sockets.in('admin').emit('comment', {content:names[0]+" 与 "+names[1]+" 对战结束 , "+names[0]+" 胜利",time:time});
		} else if (points[0].point < points[1].point && points[0].cups >= points[1].cups) {
			battle.ELO = p1;
			battle.winner = points[1].id;
			module.exports.updatePoint(points[0].id,points[0].cups - p1);
			module.exports.updatePoint(points[1].id,parseInt(points[1].cups) + p1);
			module.exports.writeLog(names[0]+" 与 "+names[1]+" 对战结束 , "+names[1]+" 胜利");
			global.sockets.in('ladder').emit('comment', {content:names[0]+" 与 "+names[1]+" 对战结束 , "+names[1]+" 胜利",time:time});
			global.sockets.in('admin').emit('comment', {content:names[0]+" 与 "+names[1]+" 对战结束 , "+names[1]+" 胜利",time:time});
		} else {
			battle.ELO = p2;
			battle.winner = points[1].id;
			module.exports.updatePoint(points[0].id,points[0].cups - p2);
			module.exports.updatePoint(points[1].id,parseInt(points[1].cups) + p2);
			module.exports.writeLog(names[0]+" 与 "+names[1]+" 对战结束 , "+names[1]+" 胜利");
			global.sockets.in('ladder').emit('comment',{content:names[0]+" 与 "+names[1]+" 对战结束 , "+names[1]+" 胜利",time:time});
			global.sockets.in('admin').emit('comment',{content:names[0]+" 与 "+names[1]+" 对战结束 , "+names[1]+" 胜利",time:time});
		}
	} else {
		battle.ELO = '-';
		battle.winner = '-';
		module.exports.writeLog(names[0]+" 与 "+names[1]+" 对战结束 , 打平");
		global.sockets.in('ladder').emit('comment',{content:names[0]+" 与 "+names[1]+" 对战结束 , 打平",time:time});
		global.sockets.in('admin').emit('comment',{content:names[0]+" 与 "+names[1]+" 对战结束 , 打平",time:time});
	}
}
//更新玩家天梯分数
module.exports.updatePoint = function (uid,point) {
	var count = 0;
	pool.getConnection(function (err, conn) {
		if (err) {
			console.log("POOL ==> " + err);
			return;
		}
	//	conn = module.exports.getConn();
		if(point < 0) point = 0;
		conn.query('UPDATE answer_user SET point=? WHERE id=?', [point,uid],
			function(error, results) {
				if(error) {
			//		console.log("ClientReady Error: " + error.message);
				//	conn.end();
					return;
				}
			}
		);
		conn.release();
	});
}
//为房间添加题干
module.exports.makeQuestionForRoom = function (id,listId) {
	var count = 0;
	pool.getConnection(function (err, conn) {
		if (err) {
			console.log("POOL ==> " + err);
			return;
		}
//		conn = module.exports.getConn();
		if(listId != null) {
			async.auto({
				rank: function (callback) {
					conn.query('SELECT questionID FROM answer_list_question WHERE listID=? ORDER BY id', [listId],
						function(error, questions) {
							if(error) {
						//		console.log("ClientReady Error: " + error.message);
							//	conn.end();
								return;
							}
							if(questions.length > 0) {
								for (var j in questions) {
									var question = questions[j];
									global.games[id].questions.push({id:question['questionID']});
								}
								callback(null, '');
						//		console.log(id+":" +count+" totals");	
							}
						}
					);
					//conn.release();
				},
				fillQuestion: ['rank', function(callback,data) {
					var totals = data.rank;
					conn.query('SELECT q.*,c.`name`,u.account FROM answer_question q LEFT JOIN answer_user u ON u.id=q.authorID LEFT JOIN answer_classify c ON c.id=q.classifyID WHERE q.id IN(SELECT questionID FROM answer_list_question WHERE listID=? ORDER BY id)', [listId],
						function(error, questions) {
							if(error) {
						//		console.log("ClientReady Error: " + error.message);
							//	conn.end();
								return;
							}
							if(questions.length > 0) {
								for (var j in questions) {
									var question = questions[j];
								//	console.log(id+" : add Questinon:"+question['id']);
									module.exports.addOptions(id,question,1);
									count++;
								}
						//		console.log(id+":" +count+" totals");	
							}
							callback();
						}
					);
					conn.release();
				}]
			}, function(err, results) {
			//	console.log('1.1: err: ', err); 
			//	console.log('1.1: results: ', results);
			});
		}
	});
}
//天梯玩家清空分数
module.exports.clearCpus = function() {
	pool.getConnection(function (err, conn) {
		if (err) {
			console.log("POOL ==> " + err);
			return;
		}
		conn.query('UPDATE answer_user SET point=?', [0],
			function(error, result) {}
		);
		conn.release();
	});
}
//为题干补充选项
module.exports.addOptions = function (id,question,type) {
	var obj = {id:question['id'],type:question['type'],src:question['src'],title:question['title'],result:question['result'],classifyID:question['classifyID'],classify:question['name'],author:question['account'],options:[]};
	pool.getConnection(function (err, conn) {
		if (err) {
			console.log("POOL ==> " + err);
			return;
		}
	//	conn = module.exports.getConn();
		conn.query('SELECT * FROM answer_option WHERE questionID=? ORDER BY RAND()', [question['id']],
			function(error, options) {
				if(error) {
			//		console.log("ClientReady Error: " + error.message);
				//	conn.end();
					return;
				}
				if(options.length > 0) {
					for (var k in options) {
						var option = options[k];
						var json = {index:option['index'],content:option['content']};
						obj.options.push(json);//添加选项到题目
					}
				//	console.log("题目"+question['id']+"成功加载了" +obj.options.length+"选项");	
					if(type == 1) {
						for (var k in global.games[id].questions) {
							var q = global.games[id].questions[k];
							if(q.id != obj.id) continue;
						//	console.log(id+" : Index : " + k + " , add question : " +q.id);	
							global.games[id].questions[k] = obj;//添加题目到固定房间
						}
					}
					else global.battles[id].questions.push(obj);//添加题目到天梯房间
				}
			}
		);
		conn.release();
	});
	
	//conn.end();
}
module.exports.writeLog = function (content) {
	var t = require('silly-datetime');
	var day = t.format(new Date(), 'YYYY-MM-DD');
	var time = t.format(new Date(), 'HH:mm');
	var obj = {
		"time": time,  
		"content": content
	};
	var str = JSON.stringify(obj);
	var fs = require('fs');
	fs.appendFile('news/'+day+'.txt', ','+str, function () {
	});
}
module.exports.getNews = function (content) {
	var t = require('silly-datetime');
	var day = t.format(new Date(), 'YYYY-MM-DD');
	var fs = require('fs');
	var data = fs.readFileSync('news/'+day+'.txt','utf-8');
	data = data.trim();
	if(data.length > 0) {
		data = '['+data.substring(1)+']';
		//var obj2 = JSON.parse(data);
		//console.log(obj2[1].content);
		return data;
	} else return '[]';
}
module.exports.getToday = function (content) {
	var t = require('silly-datetime');
	var day = t.format(new Date(), 'YYYY-MM-DD');
	return day;
}
module.exports.getYesterday = function (content) {
	var t = require('silly-datetime');
	var dd = new Date(); 
	dd.setDate(dd.getDate()-1);
	var day = t.format(dd, 'YYYY-MM-DD');
	return day;
}
module.exports.getTimeStamp = function () {
    var tmp = Date.parse(new Date()).toString();
    tmp = tmp.substr(0,10);
    return tmp;
}
//获取小程序的Token
module.exports.getToken = function (code) {
  var reqUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
  var params = {
    appid: APP_ID,
    secret: APP_SECRET,
    code: code,
    grant_type: 'authorization_code'
  };

  var options = {
    method: 'get',
    url: reqUrl+JSON.stringify(params)
  };
  console.log(options.url);
  return new Promise((resolve, reject) => {
    request(options, function (err, res, body) {
      if (res) {
        resolve(body);
      } else {
        reject(err);
      }
    })
  })
}
//获取小程序的UnionID
module.exports.getUnionID = function (code) {
	var https_request = {
		host:'api.weixin.qq.com',
		path:'/sns/jscode2session?appid='+APP_ID+'&secret='+APP_SECRET+'&js_code='+code+'&grant_type=authorization_code'
	}
	var req = https.request(https_request,function(res) {
		res.setEncoding('utf8');
		res.on('data',function(data) {
			console.log('UnionID:'+data);
		});
	});
	req.on('error', (e) => {
		console.error(e);
	});
	req.end();
}
//https://back.21eline.com/game/answer/test/12.15.log   http://phpstudy.net/c.php/115085.html(本地播放音频)